﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace JWT_AuthenticationCenter.Services
{
    public interface IJWTService
    {
        string GetToken(string UserName);
    }


    /// <summary>
    /// 备注下：代码演示的是对称加密，所以只有一个key，在返回的信息里面是没有的
    ///         PPT介绍时，说的是非对称的，那样是把解密key公开的，前面是后台用私钥加密的，
    /// 可以保证别人解密后 拿到的数据  跟前面2部分hash后的结果一致 保证没有篡改
    ///  此外，公钥不是在返回结果，那只是个打比方~
    /// </summary>
    public class JWTService : IJWTService
    {
        private readonly IConfiguration _configuration;
        public JWTService(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public string GetToken(string UserName)
        {
            var JWT_Issurer = "JWT.Auth";  //发行人（自定义标识）
            var JWT_Audience = "JWT.Bearer";  //受众人（自定义标识）
            var JWTSigningKey = _configuration["JWTSigningKey"]; //密钥 

            var claims = new[]
            {
               new Claim(ClaimTypes.Name, UserName),
               new Claim("NickName","管理员"),
               new Claim("Role","Administrator"),
            };

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JWTSigningKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var expireTime = DateTime.Now.AddMinutes(5);

            var token = new JwtSecurityToken(JWT_Issurer, JWT_Audience, claims, null, expireTime, credentials);
            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);
            return returnToken;
        }
    }
}
